package com.acme.mock;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class BankClient {

	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
    String serverResponse;
    public final static String HOST = "127.0.0.1";
    public final static String CONNECTED = "Connected to localhost in port 2004";
    public final static String BYE = "bye";
    public final static String CLIENT = "client>";
    public final static String SRV_RESP = "Server response: ";
    public final static String UNKN_FORMAT = "data received in unknown format";
    public final static String UNKN_HOST = "You are trying to connect to an unknown host!";

	BankClient() {
	}

	void run() {
		try {
			// 1. creating a socket to connect to the server
			requestSocket = new Socket(HOST, 2007);
			System.out.println(CONNECTED);
			// 2. get Input and Output streams
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			// 3: Communicating with the server
			do {
				try {
                    serverResponse = (String) in.readObject();
                    System.out.println(SRV_RESP + serverResponse);
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(System.in));
					message = reader.readLine();
					sendMessage(message);
				} catch (ClassNotFoundException classNot) {
					System.err.println(UNKN_FORMAT);
				}
			} while (!message.equals(BYE));
		} catch (UnknownHostException unknownHost) {
			System.err.println(UNKN_HOST);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			// 4: Closing connection
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println(CLIENT + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void main(final String args[]) {
		BankClient client = new BankClient();
		client.run();
	}

}
